package com.cheneyjoo.view;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cheneyjoo.base.Menu;
import com.cheneyjoo.model.RequestMessage;
import com.cheneyjoo.util.CheneyScanner;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class ManagerMenu extends Menu {
    public ManagerMenu() {
    }

    public ManagerMenu(Socket socket, PrintStream out, BufferedReader in) {
        super.setSocket(socket);
        super.setOut(out);
        super.setIn(in);
    }

    /**
     * 菜单详情页
     *
     * @throws IOException
     */
    @Override
    public void menu() throws IOException {
        boolean isShowAll = true;
        boolean isOnline = true;
        while (isOnline) {
            if (isShowAll) getUsers();
            if (!isShowAll) isShowAll = true;
            System.out.println("------------------------------------------");
            System.out.println("--用户管理");
            System.out.print("      [1]新增用户");
            System.out.println("\t [2]修改用户");
            System.out.print("      [3]删除用户");
            System.out.println("\t [4]查询用户");
            System.out.println("--试卷管理");
            System.out.print("      [5]新增试卷");
            System.out.println("\t [6]修改试卷");
            System.out.print("      [7]删除试卷");
            System.out.println("\t [8]查询试卷");
            System.out.println(" [0]退出系统");
            System.out.println("请选择对应的功能编码：");
            System.out.println("------------------------------------------");
            String menu = CheneyScanner.reader.readLine();
            switch (menu) {
                case "1":
                    addUser();
                    break;
                case "2":
                    updateUser();
                    break;
                case "3":
                    deleteUser();
                    break;
                case "4":
                    isShowAll = false;
                    getUser();
                    break;
                case "5":
                    isShowAll = false;
                    addExam();
                    break;
                case "6":
                    isShowAll = false;
                    updateExam();
                    break;
                case "7":
                    isShowAll = false;
                    deleteExam();
                    break;
                case "8":
                    new ExamMenu(super.getSocket(), super.getOut(), super.getIn()).menu();
                    break;
                default:
                    System.out.println("bye");
                    super.getOut().println("bye");
                    isOnline = false;
                    String readLine = super.getIn().readLine();
                    if ("*server close*".equals(readLine)) {
                        super.getIn().close();
                        super.getOut().close();
                    }
            }
        }

    }

    /**
     * 获取全部用户信息
     *
     * @throws IOException
     */
    private void getUsers() throws IOException {
        RequestMessage rm = new RequestMessage("user", "get", null);
        JSONObject result = getResponseResult(rm);
        Object content = result.get("content");
        System.out.println("------------------------------------------");
        if (content.getClass().equals(JSONArray.class)) {
            JSONArray users = (JSONArray) content;
            System.out.println("ID\t账户\t\t昵称");
            for (int i = 0; i < users.size(); i++) {
                JSONObject o = (JSONObject) users.get(i);
                System.out.println(o.get("id") + "\t" + o.get("account") + "\t" + o.get("name"));
            }
        }
    }

    /**
     * 添加用户页面
     *
     * @throws IOException
     */
    private void addUser() throws IOException {
        System.out.println("请输入用户名：");
        String account = CheneyScanner.reader.readLine();
        String pwd = "";
        while (1 == 1) {
            System.out.println("请输入密码：");
            pwd = CheneyScanner.reader.readLine();
            System.out.println("请确认密码：");
            String confirmPwd = CheneyScanner.reader.readLine();
            if (pwd.length() > 0 && confirmPwd.equalsIgnoreCase(pwd)) {
                break;
            }
            System.out.println("密码不一致，请重新输入");
        }
        System.out.println("请输入昵称：");
        String nikeName = CheneyScanner.reader.readLine();
        if (Optional.ofNullable(account).isPresent() && Optional.ofNullable(nikeName).isPresent()) {
            Map<String, Object> body = new HashMap<>();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("account", account);
            jsonObject.put("password", pwd);
            jsonObject.put("name", nikeName);
            body.put("body", JSON.toJSONString(jsonObject));
            RequestMessage rm = new RequestMessage("user", "register", body);
            JSONObject result = getResponseResult(rm);
            if (result.get("code").toString().equals("200")) {
                System.out.println("添加成功");
            } else {
                System.out.println("添加失败");
            }
        } else System.out.println("账号密码不能为空");
    }

    /**
     * 修改用户信息
     *
     * @throws IOException
     */
    private void updateUser() throws IOException {
        System.out.println("请输入要修改用户的ID");
        String id = CheneyScanner.reader.readLine();
        try {
            //首先校验输入的是否为正常数字类型的ID，并获取到ID
            int ID = Integer.parseInt(id);
            //校验在数据库是否存在指定ID的用户信息
            Map<String, Object> body = new HashMap<>();
            body.put("body", id);
            RequestMessage rm = new RequestMessage("user", "getById", body);
            JSONObject result = getResponseResult(rm);
            //如果存在，则进行修改信息录入
            if (result.get("code").toString().equals("200")) {
                System.out.println("请输入要用户名：");
                String account = CheneyScanner.reader.readLine();
                String pwd = "";
                while (1 == 1) {
                    System.out.println("请输入密码：");
                    pwd = CheneyScanner.reader.readLine();
                    System.out.println("请确认密码：");
                    String confirmPwd = CheneyScanner.reader.readLine();
                    if (pwd.length() > 0 && confirmPwd.equalsIgnoreCase(pwd)) {
                        break;
                    }
                    System.out.println("密码不一致，请重新输入");
                }
                System.out.println("请输入昵称：");
                String nikeName = CheneyScanner.reader.readLine();
                //录入完成发送到数据库进行修改
                if (Optional.ofNullable(account).isPresent() && Optional.ofNullable(nikeName).isPresent()) {
                    body = new HashMap<>();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", ID);
                    jsonObject.put("account", account);
                    jsonObject.put("password", pwd);
                    jsonObject.put("name", nikeName);
                    body.put("body", JSON.toJSONString(jsonObject));
                    rm = new RequestMessage("user", "update", body);
                    result = getResponseResult(rm);
                    if (result.get("code").toString().equals("200")) {
                        System.out.println(result.get("message"));
                    } else {
                        System.out.println(result.get("message"));
                    }
                } else System.out.println("账号密码不能为空");
            } else System.out.println("未检索到相关用户信息");
        } catch (NumberFormatException ex) {
            System.out.println("ID 输入格式有误");
        }
    }

    /**
     * 删除用户
     *
     * @throws IOException
     */
    private void deleteUser() throws IOException {
        System.out.println("请输入要删除用户的ID");
        String id = CheneyScanner.reader.readLine();
        try {
            int ID = Integer.parseInt(id);
            Map<String, Object> body = new HashMap<>();
            body.put("body", ID);
            RequestMessage rm = new RequestMessage("user", "delete", body);
            JSONObject result = getResponseResult(rm);
            if (result.get("code").toString().equals("200")) {
                System.out.println(result.get("message"));
            } else {
                System.out.println(result.get("message"));
            }
        } catch (NumberFormatException ex) {
            System.out.println("输入的用户ID格式有误");
        }
    }

    /**
     * 查询用户信息
     *
     * @throws IOException
     */
    private void getUser() throws IOException {
        System.out.println("请输入账户或者昵称");
        String name = CheneyScanner.reader.readLine();
        Map<String, Object> body = new HashMap<>();
        body.put("body", name);
        RequestMessage rm = new RequestMessage("user", "getByName", body);
        JSONObject result = getResponseResult(rm);
        Object content = result.get("content");
        System.out.println("------------------------------------------");
        if (content.getClass().equals(JSONArray.class)) {
            JSONArray users = (JSONArray) content;
            System.out.println("ID\t账户\t\t昵称");
            for (int i = 0; i < users.size(); i++) {
                JSONObject o = (JSONObject) users.get(i);
                System.out.println(o.get("id") + "\t" + o.get("account") + "\t" + o.get("name"));
            }
        }
    }

    /**
     * 添加试卷
     */
    private void addExam() throws IOException {
        System.out.println("请输入试卷名称：");
        String examName = CheneyScanner.reader.readLine();
        System.out.println("请输入试卷科目：");
        String categoryName = CheneyScanner.reader.readLine();
        Map<String, Object> body = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("categoryName", categoryName);
        jsonObject.put("examName", examName);
        body.put("body", JSON.toJSONString(jsonObject));
        RequestMessage rm = new RequestMessage("exam", "addExam", body);
        JSONObject result = getResponseResult(rm);
        if (result.get("code").toString().equals("200")) {
            System.out.println("添加成功!!");
            getExam();
        } else {
            System.out.println("添加失败");
        }
    }

    /**
     * 修改试卷信息
     *
     * @throws IOException
     */
    private void updateExam() throws IOException {
        getExam();
        RequestMessage rm;
        JSONObject result;
        int ExamID = 0;
        while (true) {
            System.out.println("请输入要修改的试卷ID：");
            String examID = CheneyScanner.reader.readLine();
            try {
                ExamID = Integer.parseInt(examID);
                break;
            } catch (NumberFormatException e) {
                System.out.println("试卷ID输入有误，请重新输入！");
            }
        }
        Map<String, Object> body = new HashMap<>();
        body.put("body", ExamID);
        rm = new RequestMessage("exam", "getExamById", body);
        result = getResponseResult(rm);
        if (!result.get("code").toString().equals("200")) {
            System.out.println("输入的试卷未找到！");
            return;
        }
        JSONObject examContent = JSONObject.parseObject(result.get("content").toString());
        String examName = examContent.get("examName").toString();
        System.out.println("试卷名称:" + examName + "(是否更改y/n)?");
        String choice = CheneyScanner.reader.readLine();
        if (choice.equalsIgnoreCase("y")) {
            System.out.println("请输入试卷名称：");
            examName = CheneyScanner.reader.readLine();
        }
        String categoryName = examContent.get("categoryName").toString();
        System.out.println("试卷科目:" + categoryName + "(是否更改y/n)?");
        choice = CheneyScanner.reader.readLine();
        if (choice.equalsIgnoreCase("y")) {
            System.out.println("请输入试卷科目：");
            categoryName = CheneyScanner.reader.readLine();
        }
        JSONObject exam = new JSONObject();
        exam.put("id", ExamID);
        exam.put("categoryName", categoryName);
        exam.put("examName", examName);
        body.put("body", JSON.toJSONString(exam));
        rm = new RequestMessage("exam", "updateExam", body);
        result = getResponseResult(rm);
        if (result.get("code").toString().equals("200")) {
            System.out.println("修改成功!!");
            getExam();
        } else {
            System.out.println("修改失败");
        }
    }

    /**
     * 获取试卷信息
     *
     * @throws IOException
     */
    private void getExam() throws IOException {
        RequestMessage rm = new RequestMessage("exam", "getExam", null);
        JSONObject result = getResponseResult(rm);
        Object content = result.get("content");
        System.out.println("------------------------------------------");
        if (content.getClass().equals(JSONArray.class)) {
            JSONArray exams = (JSONArray) content;
            System.out.println("ID\t试卷名称\t科目\t状态");
            for (Object exam : exams) {
                JSONObject o = (JSONObject) exam;
                System.out.println(o.get("id") + "\t" + o.get("examName") + "\t" + o.get("categoryName") + "\t" + (o.get("status").toString().equals("0") ? "未发布" : "已发布"));
            }
        }
        System.out.println("------------------------------------------");
    }

    /**
     * 删除试卷
     *
     * @throws IOException
     */
    private void deleteExam() throws IOException {
        getExam();
        RequestMessage rm;
        JSONObject result;
        int ExamID = 0;
        while (true) {
            System.out.println("请输入要删除的试卷ID：");
            String examID = CheneyScanner.reader.readLine();
            try {
                ExamID = Integer.parseInt(examID);
                break;
            } catch (NumberFormatException e) {
                System.out.println("试卷ID输入有误，请重新输入！");
            }
        }
        Map<String, Object> body = new HashMap<>();
        body.put("body", ExamID);
        rm = new RequestMessage("exam", "deleteExam", body);
        result = getResponseResult(rm);
        if (result.get("code").toString().equals("200")) {
            System.out.println("删除试卷成功");
            getExam();
        }
    }

    /**
     * 发送数据并等待回复数据
     *
     * @param rm
     * @return
     * @throws IOException
     */
    private JSONObject getResponseResult(RequestMessage rm) throws IOException {
        super.getOut().println(JSON.toJSONString(rm));
        String readLine = super.getIn().readLine();
        return JSON.parseObject(readLine);
    }
}
